package p.sunmes.les.actor;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.utils.Align;

import p.sunmes.les.action.CallAction;
import p.sunmes.les.listener.ColorChangeTouchListener;
import p.sunmes.les.util.U;

public class RadioButton extends Group {

	private Actor box;
	private Actor boxOn;
	private CallAction call;
	private boolean isBoxKeep = false;

	public Actor getBoxOn() {
		return boxOn;
	}

	public Actor getBoxOff() {
		return box;
	}

	public void setClickCall(CallAction call) {
		this.call = call;
	}

	public CallAction getCall() {
		return call;
	}

	public void setBoxKeep(boolean isKeep) {
		isBoxKeep = isKeep;
	}

	public boolean isBoxKeep() {
		return isBoxKeep;
	}

	public RadioButton(Actor box, Actor boxOn, boolean isBoxKeep) {
		this(box, boxOn);
		this.isBoxKeep = isBoxKeep;
	}

	public RadioButton(Actor box, Actor boxOn, boolean isBoxKeep,
			CallAction call) {
		this(box, boxOn);
		this.isBoxKeep = isBoxKeep;
		this.call = call;
	}

	public RadioButton(Actor box, Actor boxOn, CallAction call) {
		this(box, boxOn);
		this.call = call;
	}

	public RadioButton(Actor box, Actor boxOn) {
		this.box = box;
		this.boxOn = boxOn;

		this.setSize(box.getWidth(), box.getHeight());

		addActor(box);
		addActor(boxOn);
		box.setPosition(getWidth() / 2, getHeight() / 2, Align.center);
		boxOn.setPosition(getWidth() / 2, getHeight() / 2, Align.center);
		boxOn.setVisible(false);
		//boxOn.setTouchable(Touchable.disabled);
		U.enaTouch(box);
		box.addListener(new ColorChangeTouchListener(new CallAction() {
			public void call() {
				clicked();
			}
		}));

		if (isBoxKeep) {
			U.enaTouch(boxOn);
			boxOn.addListener(new ColorChangeTouchListener(new CallAction() {
				public void call() {
					clicked();
				}
			}));
		}
	}

	public void clicked() {
		if (!boxOn.isVisible()) {
			if (!isBoxKeep) {
				box.setVisible(false);
			} else {
				box.setTouchable(Touchable.disabled);
			}
			boxOn.setVisible(true);

			Group parent = getParent();
			if (parent != null) {
				for (Actor a : parent.getChildren()) {
					if (a instanceof RadioButton && a != this) {
						((RadioButton) a).unSelect();
					}
				}
			}
		}
		if (call != null) {
			call.call();
		}
	}

	public void unSelect() {
		if (boxOn.isVisible()) {
			if (!isBoxKeep) {
				box.setVisible(true);
			} else {
				box.setTouchable(Touchable.enabled);
			}
			boxOn.setVisible(false);
		}
	}

}
